package com.power.sifa.approve.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.plf.core.base.model.Ha_attachment;
import com.plf.core.base.service.Ha_attachmentService;
import com.plf.core.common.service.BaseServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import com.power.sifa.approve.model.Apl_agent;
import com.power.sifa.approve.dao.Apl_agentDao;
import com.power.sifa.approve.service.Apl_agentService;
import com.power.sifa.approve.model.pageInfo.Apl_agentPageInfo;

import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 *  委托代理人业务层实现
 */
@Service
public class Apl_agentServiceImpl extends BaseServiceImpl implements Apl_agentService {


    private static final String FILECARD = "filecard";

    private static final String DOCCARD = "doccard";

    private static final String FILEENTRUST = "fileentrust";

    @Resource
    private Apl_agentDao dao;
    @Resource
    private Ha_attachmentService ha_attachmentService;

    @Override
    public Apl_agent getById(Serializable id) {
        return dao.findById(id).orElse(null);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveOrUpdate(Apl_agent apl_agent) {
    	// save 如果数据库不存在这条数据，就会执行保存（即将这条数据插入到数据库）；如果数据库存在这条数据，就会根据主键去更新这条数据
        if (apl_agent.getPrimaryKey() != null) {
        	 Apl_agent apl_agentfDb = dao.findById(apl_agent.getPrimaryKey()).orElse(null);
             if(apl_agentfDb != null) {
                BeanUtils.copyProperties(apl_agent, apl_agentfDb);
                dao.save(apl_agentfDb);
                return;
             }
        }
        dao.save(apl_agent);
    }

    @Override
    public void removeById(Serializable id) {
        dao.deleteById(id);
    }

    @Override
    public Page<Apl_agent> findAll(Apl_agentPageInfo pageInfo) {
        //排序等定义
        Sort sort;
        if("asc".equals(pageInfo.getOrder())) {
            sort = Sort.by(Sort.Direction.ASC, pageInfo.getSort());
        }else {
            sort = Sort.by(Sort.Direction.DESC, pageInfo.getSort());
        }
        //分页的定义
        Pageable pageable = PageRequest.of(pageInfo.getPageNumber()<=1 ? 0 : pageInfo.getPageNumber()-1, pageInfo.getPageSize(), sort);
        //查询条件
        Specification spec = this.createSpecification(pageInfo);

        Page<Apl_agent> page = dao.findAll(spec, pageable);
        // 新增查询附件的信息
        if (CollectionUtil.isEmpty(page.getContent())) {
            return page;
        }
        getAttachFile(page.getContent(), Apl_agent::getFilecard, FILECARD);
        getAttachFile(page.getContent(), Apl_agent::getDoccard, DOCCARD);
        getAttachFile(page.getContent(), Apl_agent::getFileentrust, FILEENTRUST);
        return dao.findAll(spec, pageable);
    }

    public void getAttachFile(List<Apl_agent> agentList, Function<Apl_agent, String> function, String type) {
        if (ObjectUtil.isNotNull(agentList) && CollectionUtil.isNotEmpty(agentList)) {
            Map<String, List<String>> attchMap = new HashMap<>();
            List<String> attchId = new ArrayList<>();
            agentList.stream().forEach(item -> {
                String attchid = function.apply(item);
                if (StringUtils.isNotEmpty(attchid)) {
                    List<String> attchList = Arrays.asList(attchid.split(","));
                    attchId.addAll(attchList);
                    attchMap.put(item.getId(), attchList);
                }
            });
            // 查询对应的附件数据
            Map<String, Ha_attachment> ha_attachmentMap = ha_attachmentService.getHa_attachmentsByIds(attchId);
            if (ObjectUtil.isNotNull(ha_attachmentMap)) {
                for (String id : attchMap.keySet()) {
                    List<Ha_attachment> fileLists = new ArrayList<>();
                    List<String> attchids = attchMap.get(id);
                    for (String attchid : attchids) {
                        fileLists.add(ha_attachmentMap.get(attchid));
                    }
                    agentList.stream().filter(item -> item.getId().equals(id)).findFirst().ifPresent(obj -> {
                        if (type.equals(FILECARD)) {
                            obj.setFilecardList(fileLists);
                        } else if (type.equals(DOCCARD)) {
                            obj.setDoccardList(fileLists);
                        } else {
                            obj.setFileentrustList(fileLists);
                        }
                    });
                }
            }
        }

    }


    @Transactional(rollbackFor = Exception.class)
    public void removeByIds(List<Integer> ids) {
        dao.removeByIds(ids);
    }

    @Override
	public List<Apl_agent> findAll() {
		return dao.findAll();
	}

	@Override
	public void saveAll(List<Apl_agent> list) {
		dao.saveAll(list);
	}


    /**
     * 通过applyid查询委托代理人
     * @param applyid
     * @return
     */
    @Override
    public List<Apl_agent> getAgentByApplyid(String applyid) {
        Specification<Apl_agent> specification = (root, query, criteriaBuilder) -> query.where(
                criteriaBuilder.equal(root.get("applyid"), applyid)
        ).getRestriction();
        return dao.findAll(specification);
    }

    /**
     * 通过applyid查询委托代理人，委托代理人按照类型分类
     * @param applyid
     * @return
     */
    @Override
    public Map<Integer, List<Apl_agent>> getAgentWithGroup(String applyid) {
        List<Apl_agent> agentList = this.getAgentByApplyid(applyid);
        if (CollectionUtil.isEmpty(agentList)) {
            return null;
        }
        getAttachFile(agentList, Apl_agent::getFilecard, FILECARD);
        getAttachFile(agentList, Apl_agent::getDoccard, DOCCARD);
        getAttachFile(agentList, Apl_agent::getFileentrust, FILEENTRUST);
        return agentList.stream().collect(Collectors.groupingBy(Apl_agent::getType));
    }


    /**
     * 申请人名称查询
     * @param name
     * @return
     */
    @Override
    public List<Apl_agent> searchByName(String name) {
        List<Map<String, Object>> cardNoList = dao.searchCardNoByName("%" + name + "%");
        if (CollectionUtil.isNotEmpty(cardNoList)) {
            // 按照名称去重
            Map<String, String> distictMap = new HashMap<>();
            for (Map<String,Object> cardMap: cardNoList) {
                String cardNo = (String) cardMap.get("cardNo");
                String id = (String) cardMap.get("id");
                distictMap.put(cardNo, id);
            }
            List<String> ids = new ArrayList<>();
            for (String key : distictMap.keySet()) {
                String id = distictMap.get(key).toString();
                ids.add(id);
            }
            return dao.getByIds(ids);
        }
        return Collections.emptyList();
    }
}
